import Vue from 'vue';
import Fly from 'flyio/dist/npm/wx';
import {
	APP_KEY,
	BASE_URL
} from '@/config/index.js';
import {
	getAppSign
} from '@/utils/index.js';
import {
	jsonString
} from '@/uni_modules/uv-ui-tools/libs/function/test.js';

const fly = new Fly;
let isFirst = true;

const ignoreURI = ['/app/v6_0_0/member/findDetail'];
const config = {
	timeout: '18000',
	headers: {
		'Content-Type': 'application/json',
		'appKey': APP_KEY,
	},
	parseJson: true,
	baseURL: BASE_URL,
}

fly.config = config;

fly.interceptors.request.use((request) => {
	const token = uni.getStorageSync('loginToken');
	if (token) {
		request.headers['loginToken'] = token;
	}
	request.headers['miniAppId'] = uni.getStorageSync('miniCode');
	request.headers['sessionGenerateId'] = uni.getStorageSync('sessionGenerateId');
	const timestamp = (new Date()).valueOf();
	request.headers['timestamp'] = timestamp;
	const randomId = Math.random().toString(36).substring(2,10);
	request.headers['randomId'] = randomId;
	request.headers['appSign'] = getAppSign(timestamp, randomId);
})

fly.interceptors.response.use(
	function(response) {
		const result = response.data;
		const url = response.request.url;
		//判断登录状态
		if (result.code === 102) {
			if (!isFirst || !ignoreURI.includes(url)) {
				uni.redirectTo({
					url: '/pages/login/index'
				})
			}
		}
		if (result.code === 600) {
			uni.redirectTo({
				url: `/pages/systemMaintain/index?id=${result.data}`
			})
			return
		}
		if (result.code !== 100 && result.code != 102 && response.request.url !== '/common/shop/publickey') {
			uni.hideLoading();
			uni.showToast({
				icon: 'none',
				title: result.msg,
				duration: 3000
			})
		}
		isFirst = false;
		return response;
	},
	function (error) {
		uni.showToast({
			icon: 'none',
			title: '网络异常',
			duration: 2000
		})
	}
)

export function GET(url, data = {}) {
	return new Promise((resolve, reject) => {
		fly.get(url, data).then(res => {
			if (res) {
				resolve(res.data);
			}
		}).catch(error => {
			reject(error);
		})
	}).finally(() => {})
}

export function POST(url, data = {}) {
	return new Promise((resolve, reject) => {
		fly.post(url, data).then(res => {
			if (res) {
				resolve(res.data);
			}
 		}).catch(error => {
			reject(error);
		})
	}).finally(() => {})
}